﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

using AtletIS.Shared.Data.aDbDataSetTableAdapters;
using AtletIS.Shared.Entities;
using AtletIS.Shared.Helpers;

namespace AtletIS.Shared.Forms
{
    public partial class frmSpeaker : Form
    {

        #region Private fields

        private const int REFRESH_INTERVAL = 2000;

        private DisciplineListEntity discipline;
        private TreeNode tnDiscipline;

        private string _filePath;

        private BackgroundWorker _worker;
        private StreamWriter sw;

        #endregion

        #region Ctor

        public frmSpeaker(DisciplineListEntity discipline, TreeNode tnDiscipline)
        {
            InitializeComponent();

            this.discipline = discipline;
            this.tnDiscipline = tnDiscipline;
            this.Icon = Properties.Resources.Speaker64;
        }

        #endregion

        #region Event handlers

        // Form Load
        private void frmSpeaker_Load(object sender, EventArgs e)
        {
            this.lblTitle.Text = this.discipline.Name;

            _filePath = System.IO.Path.Combine(Application.StartupPath, "Ext", "Temp", Guid.NewGuid().ToString() + ".html");

            _worker = new BackgroundWorker { WorkerSupportsCancellation = true };
            _worker.DoWork += new DoWorkEventHandler(bw_DoWork);
            _worker.RunWorkerAsync();
        }

        // Background refresh
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                if (_worker.CancellationPending)
                {
                    e.Cancel = true;
                    break;
                }

                this.RefreshData();
                Thread.Sleep(REFRESH_INTERVAL);
            }
        }
        
        // Auto refresh
        private void chkAutoRefresh_CheckedChanged(object sender, EventArgs e)
        {
            if (this.chkAutoRefresh.Checked)
                _worker.RunWorkerAsync();
            else
                _worker.CancelAsync();
        }

        // Form closing
        private void frmSpeaker_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_worker.IsBusy)
                _worker.CancelAsync();
        }

        #endregion

        #region Private methods

        // Refreshne data raz
        private void RefreshData()
        {
            try
            {
                sw = new StreamWriter(_filePath, false, Encoding.Default);

                HtmlHelper.PrintHtmlHead(sw, "AtletIS");

                sw.WriteLine("<body>");

                #region Run

                if (tnDiscipline != null)
                {
                    if (discipline.DisciplineCode == Globals.SprintCode
                        | discipline.DisciplineCode == Globals.LongRunCode
                        | discipline.DisciplineCode == Globals.MarathonCode)
                    {
                        if (tnDiscipline.Level == 0 | tnDiscipline.Level == 2)
                        {
                            DataTable dtPerformances = DatabaseHelper.GetPerformancesByDisciplineListId(discipline.ID);
                            ResultsHelper.SummaryRunTable(sw, discipline, dtPerformances);
                        }
                        else if (tnDiscipline.Level == 1)
                        {
                            DataTable dtDisciplines = DatabaseHelper.GetDisciplineListByParentIdActive(Convert.ToInt32(tnDiscipline.Name));

                            DataTable dtSummaryPerformances = new DataTable();
                            foreach (DataRow drDiscipline in dtDisciplines.Rows)
                            {
                                DataTable dtPerformances = DatabaseHelper.GetPerformancesByDisciplineListId(Convert.ToInt32(drDiscipline["ID"]));
                                dtSummaryPerformances.Merge(dtPerformances);
                            }

                            dtSummaryPerformances.DefaultView.Sort = "Code, Result";
                            dtSummaryPerformances = dtSummaryPerformances.DefaultView.ToTable();

                            // Print summary
                            sw.WriteLine("<h3>" + tnDiscipline.Text + " - Celkové poradie" + "</h3>");
                            DataTable dtSubdisciplines = DatabaseHelper.GetDisciplineListById(Convert.ToInt32(tnDiscipline.Name));
                            if (dtSubdisciplines.Rows.Count > 0)
                            {
                                DisciplineListEntity subdiscipline = DisciplineListHelper.ConvertToEntity(dtSubdisciplines.Rows[0]);
                                ResultsHelper.SummaryRunTable(sw, subdiscipline, dtSummaryPerformances);
                            }

                            // Print disciplines
                            foreach (DataRow drDiscipline in dtDisciplines.Rows)
                            {
                                sw.WriteLine("<h3>" + drDiscipline["Name"].ToString() + "</h3>");
                                DisciplineListEntity childDiscipline = DisciplineListHelper.ConvertToEntity(drDiscipline);
                                DataTable dtPerformances = DatabaseHelper.GetPerformancesByDisciplineListId(childDiscipline.ID); // taPerformances.GetByDisciplineListId(childDiscipline.ID);
                                ResultsHelper.SummaryRunTable(sw, childDiscipline, dtPerformances);
                            }
                        }
                    }
                }

                #endregion

                #region Field

                if (discipline.DisciplineCode == Globals.ThrowsCode)
                    ResultsHelper.ThrowsTable(sw, discipline);

                if (discipline.DisciplineCode == Globals.HorJumpCode)
                    ResultsHelper.HorJumpsTable(sw, discipline);

                if (discipline.DisciplineCode == Globals.VerJumpCode)
                    ResultsHelper.VerJumpsTable(sw, discipline);

                #endregion

                sw.WriteLine("</body>");
                sw.WriteLine("</html>");

                this.tsslRefresh.Text = "Refreshed: " + DateTime.Now.ToLongTimeString();
            }
            catch { }
            finally
            {
                sw.Close();
                sw.Dispose();

                this.wbSpeaker.Navigate(_filePath);
            }
        }

        #endregion

    }
}
